package com.wang.mandkey.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.wang.mandkey.App;
import com.wang.mandkey.R;
import com.wang.mandkey.bean.AdapterCharactor;
import com.wang.mandkey.net.ConnecterPool;
import com.wang.mandkey.net.INetCallBack;
import com.wang.mandkey.tool.RemoteOperateImpl;
import com.wang.mandkey.tool.SeariesTool;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.ProjectEnvironment;
import com.wang.mandkey.utils.SharePersistent;
import com.wang.mandkey.utils.StringUtils;
import com.wang.mandkey.views.KeyBoardView;
import com.wang.mandkey.views.PointFBean;

public class KeyBoardActivity extends BaseActivity implements INetCallBack{

	private LinearLayout mLinearLayoutKeylist;
	private KeyBoardView mKeyBoradView;
	private TextView textView;
	private ListView listViewCharactor;
	private ScrollView scrollViewCharactor;
	public  String tag="KeyBoardActivity";
	private ArrayList<PointFBean> mArrayListpointFlist = null;
	private Animation animationSlideInRight,animationSlideOutRight;
	private  Dialog dlg=null;
	
	protected Character[] keys={
			'A','B','C','D','E','F','G',
			'H','I','J','K','L','M','N',
			'O','P','Q','R','S','T','U',
			'V','W','X','Y','Z'
			};
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		setContentView(R.layout.keyboard);
		
		mArrayListpointFlist=new ArrayList<PointFBean>();
		
		String pfname =getIntent().getStringExtra(ProjectEnvironment.STRING_CASE_KEY);
		 if(!StringUtils.isEmpty(pfname)){
			 ArrayList<PointFBean> caselist = SeariesTool.loadPointFList(this,pfname);
				if(null!=caselist){
					mArrayListpointFlist.addAll(caselist);
				}
		 }
		
		
		ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED=false;//键盘解锁
		setUpView();
		initKeyBoard();
		
		animationSlideInRight=AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
		animationSlideOutRight=AnimationUtils.loadAnimation(this, R.anim.slide_out_right);
		
	}
	public void setUpView(){
		mKeyBoradView = (KeyBoardView) findViewById(R.id.mouseView);
		textView = (TextView) findViewById(R.id.textViewNotify);
		listViewCharactor=(ListView)findViewById(R.id.listViewCharactor);
		mLinearLayoutKeylist=(LinearLayout)findViewById(R.id.linearLayoutKeylist);

//		mLinearLayoutKeylist.setVisibility(View.GONE);//第一次不显示字母选择列表      
		
		listViewCharactor.setAdapter(new AdapterCharactor(this, Arrays.asList(keys)));
		listViewCharactor.setScrollbarFadingEnabled(true);
		listViewCharactor.setVerticalScrollBarEnabled(false);
		listViewCharactor.setScrollbarFadingEnabled(true);
		listViewCharactor.setItemsCanFocus(false);
		mKeyBoradView.setRemoteOperateImpl(new RemoteOperateImpl(ConnecterPool.getConnectorByKey(ConnecterPool.STRING_CKEY),this));
		listViewCharactor.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				Character var = keys[position];
			
				int indexres=isKeyCodeExistInList(var);
				if(indexres!=-1){
					//存在就取消
					mArrayListpointFlist.remove(indexres);
				}else{
					//不存在就添加
					PointFBean pointF = new PointFBean();
					Point randPoint = Tool.getRandomPoint(new Point(200,300));
					pointF.setX(randPoint.x+50);
					pointF.setY(randPoint.y+50);
				
					int radius=(int)ProjectEnvironment.FLOAT_BUTTON_RADIUS;
					String radioStr=SharePersistent.getPerference(KeyBoardActivity.this, ProjectEnvironment.STRING_PROJECT_RADIUS_KEY);
					 if(!StringUtils.isEmpty(radioStr)){
						 ProjectEnvironment.FLOAT_BUTTON_RADIUS=radius=Integer.parseInt(radioStr);
					 }
					pointF.setRadius(radius);
					pointF.setStringKey(String.valueOf(keys[position]));
					
					mArrayListpointFlist.add(pointF);
				}
				mKeyBoradView.invalidate();	
			}
		});
		

		
//		mKeyBoradView.measure(300, 300);
//		mKeyBoradView.setWidthAndroidHeight(300,400);
//		mKeyBoradView.invalidate();
		
//		mKeyBoradView.setLayoutParams(new RelativeLayout.LayoutParams(300,400));
		
	}
	
	  
	
	@Override
	protected void onResume() {
		super.onResume();
		if(ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED==false){
			Toast.makeText(this, getResources().getString(R.string.keyboard_activity_unlock_notify), Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(this, getResources().getString(R.string.keyboard_activity_lock_notify), Toast.LENGTH_SHORT).show();	
		}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_keyboard, menu);
		return true;
	}
	
	
	public void initKeyBoard(){
		mKeyBoradView.setmArrayListPointbeans(mArrayListpointFlist);
		mKeyBoradView.setHandler(mHandler);
	/*	for (int i = 0; i <keys.length; i++) {
			PointFBean pointF = new PointFBean();
			Point randPoint = Tool.getRandomPoint(Tool.getDisplayMetrics(this));
			pointF.setX(randPoint.x-50);
			pointF.setY(randPoint.y-50);
			Point point=Tool.getDimensionsByDimens(mKeyBoradView.getLayoutParams().width, mKeyBoradView.getLayoutParams().height);
			pointF.setX(point.x);
			pointF.setY(point.y);
			pointF.setRadius(50);
			pointF.setStringKey(String.valueOf(keys[i]));
			pointFlist.add(pointF);
		}*/
	
	}
	/**
	 * 判断是否存在某个
	 * @param charac
	 * @return
	 */
    public int isKeyCodeExistInList(Character charac){
    	int index=-1;
    	for(int i=0,isize=mArrayListpointFlist.size();i<isize;i++){
    		int chac = mArrayListpointFlist.get(i).getKeyCode();
    		if(charac==chac){
    			index=i;
    			break;
    		}
    	}
    	return index;
    }	

    
  
	/**
	 * 当用户选择了当前ItmeSelected
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(tag, item.getItemId() + ":" + item.getItemId());
		switch (item.getItemId()) {

		case R.id.menuItemLock:
			
			Log.i(tag, "锁定");
			if(!ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED ){
				ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED = true;
				mLinearLayoutKeylist.startAnimation(animationSlideOutRight);
				animationSlideOutRight.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						mLinearLayoutKeylist.setVisibility(View.GONE);
					}
				});
			}else{
				Toast.makeText(this, getResources().getString(R.string.menu_lock_already), Toast.LENGTH_SHORT).show();
			}
			
			
			break;
		case R.id.menuItemExit:
			App.exitApp(KeyBoardActivity.this);
			break;
		case R.id.menuItemToMouse:
			Tool.startOtherActivity(this, MouseActivity.class);
		break;
		
		case R.id.menuItemUnLock:
			Log.i(tag, "解锁");
			if(ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED){
				ProjectEnvironment.BOOLEAN_LOCK_KEYBOAED = false;
				mLinearLayoutKeylist.setVisibility(View.VISIBLE);
				mLinearLayoutKeylist.startAnimation(animationSlideInRight);	
			}else{
				Toast.makeText(this, getResources().getString(R.string.menu_unlock_already), Toast.LENGTH_SHORT).show();
			}
			
			break;
			
		case R.id.menuItemSave:
			Log.i(tag, "保存键盘方案");

			final View view=View.inflate(this, R.layout.dialog_savename, null);
			final EditText fnameEditText=(EditText) view.findViewById(R.id.editTextFileName);
			
//			Builder alertdlgBuilder=Tool.createADialig(this, view);
//			        alertdlgBuilder.setTitle(getResources().getString(R.string.keyboard_activity_file_name));
			        
				  dlg = new AlertDialog.Builder(this)
				 .setTitle(getResources().getString(R.string.keyboard_activity_file_name))
				 .setView(view)
				 .setPositiveButton(getResources().getString(R.string.confirm), new OnClickListener() {
									@Override
							public void onClick(DialogInterface dialog, int which) {
								String fname = fnameEditText.getText().toString().trim();
								if (StringUtils.isEmpty(fname)) {
									Animation animation = AnimationUtils.loadAnimation(KeyBoardActivity.this, R.anim.shake);
									fnameEditText.startAnimation(animation);
								} else {
								try {
										SeariesTool.savePointFBean(KeyBoardActivity.this,mArrayListpointFlist,fname);
									} catch (IOException e) {
										e.printStackTrace();
										Log.i(tag, "error:" + e.toString());
										Toast.makeText(KeyBoardActivity.this,getResources().getString(R.string.keyboard_activity_save_fail),Toast.LENGTH_SHORT).show();
										dlg.dismiss();
									}
								}
							 }
					    })
			     .setNegativeButton(getResources().getString(R.string.cancell), new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dlg.dismiss();
						}}).create();
				  
			dlg.show();
			break;
			
		default:
			break;
		}
		return false;
	}
	/*
	 用来接受keyboradview发送过来的事件
	 */
	public Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle bundle = msg.getData();
			String[] arrays = bundle.getStringArray(ProjectEnvironment.STRING_LOCATION_KEY);
			textView.setText(/*arrays[0] + ":" + arrays[1] + ":" +*/"按下:"+ arrays[2]);
		};
	};
	@Override
	public void OnFinish() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void OnIntercepted(String source) {
		// TODO Auto-generated method stub
//		Toast.makeText(this, getResources().getString(R.string.app_lost_host), Toast.LENGTH_SHORT).show();
//		this.finish();
		Tool.doNetLost(this);
		
	}
	@Override
	public void OnStart() {
		// TODO Auto-generated method stub
		
	}


}
